﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Licenta_Stomatologie.Panels
{
    public partial class AppointmentCreatePanel : UserControl
    {
        private int[] pacientIds = new int[1000];
        private String[] appointmentTypes = new String[] { "Control", "Interventie medicala" };

        public AppointmentCreatePanel()
        {
            InitializeComponent();
            fillWithPacients();
        }

        private void fillWithPacients()
        {
            ProjectDBEntities db = new ProjectDBEntities();

            IEnumerable<Pacient> pacienti = db.Pacients.Where(p => p.id > 0);

            int i = 0;
            foreach (Pacient pacient in pacienti)
            {
                cboxPacient.Items.Add(pacient.nume + " " + pacient.prenume);
                pacientIds[i] = pacient.id;
                i++;
            }
        }

        private bool collidesWithAppointment()
        {
            ProjectDBEntities db = new ProjectDBEntities();
            DateTime selectedDate = new DateTime(dtpAppointmentDate.Value.Year, dtpAppointmentDate.Value.Month, dtpAppointmentDate.Value.Day, dtpAppointmentTime.Value.Hour, dtpAppointmentTime.Value.Minute, dtpAppointmentTime.Value.Second); 
            IEnumerable<Appointment> apps = db.Appointments.Where(a => a.id > 0);
            int duration = int.Parse(tbAppointmentDuration.Text);

            foreach (Appointment app in apps)
            {
                if (app.date.Value.AddMinutes((double)app.duration) > selectedDate)
                {
                    if (selectedDate.AddMinutes((double)duration) < app.date.Value)
                    MessageBox.Show(app.date.Value.AddMinutes((double)app.duration).ToString() + " " + selectedDate.ToString());
                    return true;
                }
                /*
                if (selectedDate.AddMinutes((double)duration) > app.date.Value)
                {
                    MessageBox.Show(selectedDate.AddMinutes((double)duration).ToString() + " " + app.date.Value.ToString());
                    return true;
                }
                */
            }

            return false;
        }

        private bool checkData()
        {
            foreach (TextBox tb in this.Controls.OfType<TextBox>())
            {
                if (tb.Text.Length == 0)
                {
                    return false;
                }
            }

            foreach (ComboBox cb in this.Controls.OfType<ComboBox>())
            {
                if (cb.SelectedIndex == -1)
                {
                    return false;
                }
            }

            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(Helpers.UserMessages.APPOINTMENT_CREATE_CANCEL, "Confirmation", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                this.Controls.Clear();
                this.Controls.Add(new Panels.Dashboard());
            }
        }

        private void cboxPacient_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(String.Format("Selected pacient : {0} with id : {1}",cboxPacient.SelectedItem,pacientIds[cboxPacient.SelectedIndex]));
        }

        private void dtpAppointmentDate_ValueChanged(object sender, EventArgs e)
        {
            ProjectDBEntities db = new ProjectDBEntities();

            DateTime selectedDate = dtpAppointmentDate.Value.Date;          

            IEnumerable<Appointment> apps = db.Appointments.Where(a => a.date.Value.Year == selectedDate.Year && a.date.Value.Month == selectedDate.Month && a.date.Value.Day == selectedDate.Day);

            int appointmentsCount = apps.Count();

            if (appointmentsCount == 0)
            {
                dgvOtherAppointments.Visible = false;
                lblOtherAppointments.Text = "Nu exista alte programari in ziua selectata";
            }
            else
            {
                dgvOtherAppointments.Visible = true;

                DataTable dt = new DataTable("appointments");

                DataColumn[] columns = new DataColumn[] { new DataColumn("id",typeof(int)), new DataColumn("Pacient",typeof(String)), new DataColumn("Ora inceperii",typeof(String)) , new DataColumn("Durata",typeof(String)), new DataColumn("Tip",typeof(String)) };

                dt.Columns.AddRange(columns);

                foreach (Appointment a in apps)
                {
                    Pacient pac = db.Pacients.First(p => p.id == a.pacientId);

                    dt.Rows.Add(a.id, pac.nume + " " + pac.prenume, a.date.Value.ToShortTimeString() ,a.duration, appointmentTypes[(int) a.type]);
                }

                dgvOtherAppointments.DataSource = dt;

                dgvOtherAppointments.Columns["id"].Visible = false;
            }
        }

        private void btnCreateAppointment_Click(object sender, EventArgs e)
        {
            if (checkData())
            {
                ProjectDBEntities db = new ProjectDBEntities();

                Appointment app = new Appointment();

                DateTime when = new DateTime(dtpAppointmentDate.Value.Year, dtpAppointmentDate.Value.Month, dtpAppointmentDate.Value.Day, dtpAppointmentTime.Value.Hour, dtpAppointmentTime.Value.Minute, dtpAppointmentTime.Value.Second);

                app.date = when;
                app.duration = int.Parse(tbAppointmentDuration.Text);
                app.pacientId = pacientIds[cboxPacient.SelectedIndex];
                app.type = cboxAppointmentType.SelectedIndex;
                app.cost = int.Parse(tboxCost.Text);
                app.achitat = cboxAchitat.SelectedIndex;
                if (int.Parse(tboxCost.Text) == 0)
                {
                    app.achitat = 1;
                }


                db.Appointments.Add(app);

                db.SaveChanges();

                MessageBox.Show(Helpers.UserMessages.APPOINTMENT_CREATE_SUCCESS);

                this.Controls.Clear();
                this.Controls.Add(new Panels.Dashboard());
            }
            else
            {
                MessageBox.Show("Date invalide");
            }
        }

        private void dgvOtherAppointments_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int appointmentId = (int) dgvOtherAppointments.SelectedRows[0].Cells["id"].Value;

            this.Controls.Clear();
            this.Controls.Add(new Panels.AppointmentEditPanel(1));
        }
    }
}
